/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.gateway.config

import com.alibaba.fastjson.JSONObject
import com.gitee.minimalismstyle.fresh.common.core.const.CacheConst
import com.gitee.minimalismstyle.fresh.common.core.extra.log
import com.gitee.minimalismstyle.fresh.gateway.route.MyRouteDefinition
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.web.context.WebServerInitializedEvent
import org.springframework.cloud.gateway.route.RouteDefinitionRepository
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.event.EventListener
import org.springframework.core.annotation.Order
import org.springframework.data.redis.connection.Message
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.listener.ChannelTopic
import org.springframework.data.redis.listener.RedisMessageListenerContainer
import org.springframework.scheduling.annotation.Async
import reactor.kotlin.core.publisher.toMono

@Configuration
class GatewayRouterConfig(val redisTemplate: StringRedisTemplate) {

    @Autowired
    val routeDefinitionRepository: RouteDefinitionRepository? = null

    @Bean
    fun redisContainer(): RedisMessageListenerContainer? {
        val container = RedisMessageListenerContainer()
        redisTemplate.connectionFactory?.let { container.setConnectionFactory(it) }
        container.addMessageListener( { _: Message?, _: ByteArray? ->
            log.warn("重新加载路由事件")
            updateRoutes()
        }, ChannelTopic(CacheConst.ROUTES_RELOAD_TOPIC))
        return container
    }

    @Async
    @Order
    @EventListener(WebServerInitializedEvent::class)
    fun updateRoutes(){
        if(redisTemplate.hasKey(CacheConst.ROUTES_KEY)){
            var routesString = redisTemplate.opsForValue().get(CacheConst.ROUTES_KEY)
            log.debug(routesString)

            JSONObject.parseArray(routesString, MyRouteDefinition::class.java).forEach{
                routeDefinitionRepository!!.save(it.toMono())
                        .subscribe()
            }
        }
    }

}
